/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tracemap.services;

import java.util.Random;

import com.tarcemap.gpsmobileappgui.WannaDebugTableActivity;
import com.tracemap.gpslocation.GPSManager;
import com.tracemap.gpslocation.GPSReadListener;
import com.tracemap.gpslocation.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.


/**
 * This is an example of implementing an application service that runs locally
 * in the same process as the application.  The {@link LocalServiceActivities.Controller}
 * and {@link LocalServiceActivities.Binding} classes show how to interact with the
 * service.
 *
 * <p>Notice the use of the {@link NotificationManager} when interesting things
 * happen in the service.  This is generally how background services should
 * interact with the user, rather than doing something more disruptive such as
 * calling startActivity().
 */

public class LocationSender extends Service implements GPSReadListener {
    private NotificationManager mNM;
    GPSManager gps;
    GPSReadListener mGPSListener;

	public GPSReadListener getmGPSListener() {
		return mGPSListener;
	}

	public void setmGPSListener(GPSReadListener mGPSListener) {
		this.mGPSListener = mGPSListener;
	}

	private double mLat = 0;
    private double mLng = 0;
 // Random number generator
    
    private final Random mGenerator = new Random();
    
    
    public double getmLat() {
		return mLat;
	}

	public void setmLat(double mLat) {
		this.mLat = mLat;
	}

	public double getmLng() {
		return mLng;
	}

	public void setmLng(double mLng) {
		this.mLng = mLng;
	}

	
    
    @Override
    public void onCreate() {
    	Log.i("LocalService","onCreate");
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        LocationManager lm= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        gps = GPSManager.getInstance(lm) ;
		gps.setReadListener(this);
		
		if (!gps.isProcessing()) {
			gps.start();
		}
        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	gps.stopGPS();
		gps.closeGPS();
		gps = null;
    	
		// Cancel the persistent notification.
        mNM.cancel(R.string.local_service_started);

        // Tell the user we stopped.
        Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        public LocationSender getService() {
            return LocationSender.this;
        }
    }
    
    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        return true;
    }
    
    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
    /**
     * Show a notification while this service is running.
     */
    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.local_service_started);

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.arrow2, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, WannaDebugTableActivity.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.local_service_started, notification);
    }

	@Override
	public void read(double lat, double lng, double alt) {
		
		mLat = lat;
		mLng = lng;
		// Tell the user we stopped.
		Context context = getApplicationContext();
		CharSequence text = "Localtion: latitude:"+String.valueOf(lat)+" longtitude:"+String.valueOf(lat);
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
		if (mGPSListener != null)
		{
			mGPSListener.read(lat, lng, alt);
		}
		
	}

	@Override
	public void readException(Exception ex) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void readError(Exception ex, String errorMessage) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void TimeOut() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void choseDevices() {
		// TODO Auto-generated method stub
		
	}
}

